<!--导航按钮-->
<script> 
	   function checkInt(o){ 
			theV=isNaN(parseInt(o.value))?0:parseInt(o.value); 
			if(theV!=o.value){o.value=theV;} 
			txtTotal.value=txtAmount.value*txtPrice.value; 
		} 
		function checkP(o){ 
				theV=isNaN(parseFloat(o.value))?0:parseFloat(o.value);
				theV=parseInt(theV*100)/100; 
				if(theV!=o.value){ 
					theV=(theV*100).toString(); 
					theV=theV.substring(0,theV.length-2)+"."+theV.substring(theV.length-2,theV.length) 
					o.value=theV; 
				} 
                                if (txtAmount.value) {
                                    var _val = txtAmount.value + '',
                                        _b   = _val.match(/\d+(?:\.\d+)?$/),
                                        _p   = parseFloat(_b[0]),
                                        _v   = parseFloat(parseFloat(txtPrice.value) - _p);
                                    _v = _v.toFixed(2);
                                    _v = isNaN(_v) ? txtPrice.value : _v;
                                } else {
                                    var _v   = 0;
                                }
			txtTotal.value = _v; 
		 } 
        function checkMoney(dom) {
            _nomer = Number(txtTotal.value);
            //alert(_nomer);
            if ( _nomer<0) {
                alert('实收金额必须大于或等于应收金额');
            }
        }
</script>

<div id="main">
<div class="sbmit_list" id="order_container">
    
    <ul id="menu12">
        

            <li><a href="#" class="drop">账户余额付款</a>
               
                      <div class="dropdown_1column " style="width:680px" id="kkkkk">       
                       应收金额：<span class="kkss" style="color: red; font-size: 24px; font-weight: bold;"><{$aCart.promotion_subtotal|cur_odr}></span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
                       账户余额：<span style="color: red; font-size: 24px; font-weight: bold;" class="kkss1"><{$member.advance|cur_odr}></span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;   
                     <span class="zhye_other"><{t}>余额不足，还差：<span class="zhye_other_val" style="color:red;font-size: 24px;" ></span></br>请选择以下方式支付差额。<{/t}><br/><label style="font-size:18px;"><input type="radio" value="1" name="other_pay" checked="checked"/><font style="font-size: 24px">现金付款</font></label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label style="font-size:18px;"><input type="radio" value="2" name="other_pay"/><font style="font-size: 24px ">刷卡付款</font><label></span><br /><br />
                                 账户密码：<input  value="" name="password" type="password" id="webpos_password"/><span id="dd_list" class="dd_add_info" style="color: #006600;"></span><br/>
                       <input type="button" style="cursor:pointer" id="add_yuamount" name="amount_submit" class="submdeoe"  value="确认付款" />
                       </div>        
           </li>

           <li><a href="#" class="drop">现金付款</a>
                    
                        <div class="dropdown_1column jisuan" id="sssss">        
                            应收金额：<span class="kkdd"><span  style="color: red; font-size: 18px; line-height: 40px; font-weight: bold; "></span><input id=txtAmount value="￥<{$aCart.promotion_subtotal}>" readOnly="true" style="border:none; color: red; font-size: 24px; height:28px;font-weight: bold;margin-top:-6px;"/></span><br/>  
                            实收金额：<span style="color: red; font-size: 18px; line-height: 40px; font-weight: bold;">￥</span><input id=txtPrice value="0" class="sddss" style=" width: 150px; height: 28px; padding-left: 5px; color: red; font-size: 20px; font-weight: bold;" onkeyup="checkP(this);" onpaste="checkP(this);" oncut="checkP(this);" ondrop="checkP(this);" onchange="checkP(this);" onblur="checkMoney(this)" /><br/>
                            找零：<input id=txtTotal value=0 readOnly="true" style="border-right-width:0px; margin-right:0px; border: none; color: red; font-size: 20px; font-weight: bold;margin-top:-8px;"/> <br/><br/>
                            <input type="submit" style="cursor:pointer" id="add_xjamount" name="amount_submit" class="submdeoe"  value="确认付款" />
                            <br/>
                        </div> 
                </li>

                <li><a href="#" class="drop">刷卡付款</a>    
                    <div class="dropdown_1column" id="fffff">        
                        <font style="font-size: 18px;">刷卡金额：</font><span style="color: red; font-size: 24px; font-weight: bold;" class="kkff"><b><{$aCart.promotion_subtotal|cur_odr}></b></span><br/><br/>  
                          <input type="submit" onClick="delete_confirm" style="cursor:pointer" id="add_skamount" name="amount_submit" class="submdeoe"  value="确认付款" />
                        </div>        
                </li>

                   <li style="margin-left:280px; display: none;"><a href="#" class="drop">发票信息</a>    
                        <div class="dropdown_1column kllsldk">        
                          
                            <div id="order_invoice" class="order-section order-invoice">
                               <div class="order-section-title"><b>发票信息</b></div>
                                <div class="order-section-content">
                                  <table>
                                    <tbody>
                                      <tr>
                                        <td>
                                            <ul class="lkksk" style=" float: left;">
                                            <li style="float: left"><input type="radio" name="payment[tax_type]" id="for_invoice_false" value="false" class="action-select-invoice" checked="checked"> <label for="for_invoice_false">不需要发票</label></li>
                                            <li style="float: left"><input type="radio" name="payment[tax_type]" id="for_invoice_personal" value="personal" class="action-select-invoice"> <label for="for_invoice_personal">个人发票 <{if $tax_setting.personal_tax_ratio}>(税率<{$tax_setting.personal_tax_ratio*100}>%)<{/if}></label></li>
                                            <li style="float: left"><input type="radio" name="payment[tax_type]" id="for_invoice_company" value="company" class="action-select-invoice"> <label for="for_invoice_company">公司发票 <{if $tax_setting.company_tax_ratio}>(税率<{$tax_setting.company_tax_ratio*100}>%)<{/if}></label></li>
                                          </ul>
                                        </td>
                                      </tr>
                                      <tr class="fold">
                                        <td><input type="hidden" name="payment[is_tax]" value="false"><label for="for_tax_company"><{t}>发票抬头<{/t}>：</label> <input type="text" name="payment[tax_company]" id="for_tax_company" vtype="required" data-caution="请填写发票抬头"></td>
                                      </tr>
                                      <{if $tax_setting.tax_content}>
                                      <tr class="fold">
                                          <td><label for="for_tax_content"><{t}>发票内容<{/t}>：</label>
                                          <{input type='select' options=$tax_setting.tax_content name="payment[tax_content]" id="for_tax_content" vtype="required" data-caution="请选择发票内容"}>
                                        </td>
                                      </tr>
                                      <{/if}>
                                    </tbody>
                                  </table>
                                </div>
                              </div>
                              <input type="submit" name="amount_submit" style="cursor:pointer" class="submdeoe" value="确认打印" /> 
                        </div>        
                </li>
                <li style="margin-left: 130px;"><a href="#" class="drop">优惠券</a>    
                        <div class="dropdown_1column"  style="width: 650px;  margin-left:-606px;">        
                          <{include file='site/cart/checkout/local_coupon.html' app='b2c'}>           
                        </div>        
                </li>
                  <li ><a href="#" class="drop">会员充值</a> 
                     
                       
                    <div class="dropdown_1column sdffsd" style="margin-left: -314px;">        
                      <form class="form" style=""  method="post" action="<{link app=b2c ctl=site_cart act=checkout_vacancies}>">
                           输入充值金额：<input type="text" name="yu_amount" autocomplete="off" class="sddss" value="" /><br/><br/>  
                           <input type="submit" name="amount_submit" class="submdeoe"  value="确认充值"  style="margin-left: 98px; cursor:pointer"/>
                       </form>
                         
                        </div>        
                </li>
                <li ><a href="#" class="drop">充值卡</a> 
                     
                       
                    <div class="dropdown_1column sdffsd" style="margin-left: -356px;">        
                          <form action="<{link app=b2c ctl="site_member" act="gc_dopayment" arg0="giftcard"}>" method="post"  id="giftcard" extra="subOrder" class="mod-content signupin-content">
                          <input type="hidden" name="payment[member_id]" value="<{$member_id}>" />
                          <input type="hidden" name="payment[return_url]" value="<{$return_url}>" /> 
                          <input type="hidden" name="is_store" value="1" />
                                    <ul>

                                        <li class="form-item" style="width: 400px; margin-bottom: 30px; padding-top: 50px; ">
                                            <label for="" class="form-label" style="width: 150px; font-size: 20px;" >兑换卡卡号：</label>
                                            <span class="form-act">
                                                                        <{input style="font-size:18px; hight:40px;  border:1px solid #ccc; padding:0px;" class="inputstyle" type="unsigned" name="giftcard[gcard_code]" vtype="required" id='deposit' data-caution="请填写兑换卡号！"}>
                                            </span>
                                        </li>
                                        <li class="form-item-normal" style="padding-bottom: 30px; margin-left: 88px;">
                                            <label for="" class="form-label"></label>
                                            <span class="form-act" >
                                             <{button class="btn btn-import btn-big submdeoe" style="width:100px; hight:30px;"  type="submit" isDisabled="true" label=$___b2c="确认充值"|t:'b2c' rel="_request"}></td>
                                            </span>
                                        </li>
                                    </ul>
                                </form>
                        </div>        
                </li>
                  
        </ul>
</div>
  <!--导航按钮-->
     
           
    <{if $is_input != 1}>
    <div class="cart-tj">
     <div style="float:right; line-height:20px; padding-bottom:5px; padding-top:1px; padding-right:50px;"><font style="vertical-align:middle; font-size:14px; line-height:30px; ">货号：</font><input type="text" id="bn_add_cart"  placeholder="输入货号/条码扫描" style="vertical-align:middle; width:223px; padding:5px; height:20px;"  /></div>
   <div class="bn_add_info"></div>
    </div>
    <{/if}>
<div id="main" style="background: #FFF;">
<div class="black10"></div>
  <{if $is_empty}>
    <{include file="site/cart/storecart_empty.html" app=b2c}>
  <{else}>
  
  <!-- 购物车主体 -->
  <div id="cart_container" class="cart-container">
    <{include file="site/cart/storecart_main.html" app=b2c}>
  </div>
  <{/if}>

</div>

    <div style="display: none;">
 
  <!-- checkout主体 -->
  <div id="order_container" class="order-container" style="margin-top: -29px;">
    <!-- checkout内容 -->
    <form action="<{link app=b2c ctl='site_order' act='create'}>" method="post">
      <{if $is_fastbuy}>
        <input type="hidden" name="isfastbuy" value="true" />
      <{/if}>
      <{if $cart_type eq 'x'}><input type="hidden" name="type" value="x" /><{/if}>
      <input type="hidden" name="purchase[addr_id]" value="<{$def_addr.addr_id}>" />
      <input type="hidden" name="purchase[def_area]" value="<{$def_area}>" />
      <input type="hidden" name="md5_cart_info" value="<{$md5_cart_info}>" />
      <input type="hidden" name="extends_args" id="op_extends_args" value="<{$json_args}>" />
      <input type="hidden" name="store_id"  value="<{$local_store.local_id}>" />

      <!-- 订单信息填写 -->
      <div id="order_main" class="order-main">
        <{if $minfo}>
        <{include file='site/cart/checkout/goods.html' app='b2c'}>
        <{/if}>

        <{include file='site/cart/checkout/local_shipping.html' app='b2c'}>

        <{include file='site/cart/checkout/local_delivery.html' app='b2c'}>

        <{include file='site/cart/checkout/local_payment.html' app='b2c'}>

        <{if $tax_setting}>
        <{include file='site/cart/checkout/invoice.html' app='b2c'}>
        <{/if}>

        <{include file='site/cart/checkout/cart_main.html' app='b2c'}>
      </div>

      <!-- 结算信息 -->
      <table id="order_clearing" class="order-clearing">
        <caption>结算信息</caption>
        <tbody>
          <tr>
            <td class="order-infor">
              <{if $aCart.promotion.order}>
              <!-- 订单优惠 -->
              <div class="order-promotion" id="order_promotion">
                <h3><a href="javascript:void(0);" class="btn-collapse action-toggle">-</a>订单优惠</h3>
                <ul class="content">
                  <{foreach from=$aCart.promotion.order item=item}>
                  <li><b>[<{$item.desc_tag}>]</b><{$item.name}></li>
                  <{/foreach}>
                </ul>
              </div>
              <{/if}>

              <{include file='site/cart/checkout/coupon.html' app='b2c'}>

              <{if $point_dis_html}>
              <!-- 积分抵扣 -->
              <{$point_dis_html}>
              <{/if}>

              <div id="order_remark" class="order-remark"><label for="">订单备注：</label><textarea name="memo" class="action-remark-textarea" cols="60" rows="3" placeholder="请在此填写您对该订单或商品的特殊要求或说明，最多300字。"></textarea></div>
            </td>

            <!-- 订单价格 -->
            <td id="order_price" class="order-price">
             <{include file='site/cart/checkout/local_checkout_total.html' app='b2c'}>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  </div>
</div>
<script type="text/javascript">
//验证会员密码
$('webpos_password').addEvent("keyup",function(E){
                        <{if !$member.uname}>
                            alert('请先登录会员！');
                            return false;
                        <{/if}>
			var password = this.value;
                        var url = '<{link app=b2c ctl=site_storepassport act=webpos_passwordcheck}>';
                        var ps_add_info = $$(".dd_add_info");
                        if(password.length > 5){
                            var myRequest = new Request.JSON({
                                url: url,
                                method: 'post',
                                onRequest: function(){
                                    ps_add_info.set('html','');
                                },
                                onSuccess: function(responseText){
                                    if(responseText.ret == "会员密码正确!"){
                                         ps_add_info.set('html',responseText.ret);
                                    }
                                   
                                },
                                onFailure: function(){
                                    ps_add_info.set('html','');
                                }
                            });
                            var data = "password=" + password;
                            myRequest.send(data);
                        }
 });
    
<{if $money_format}>priceControl.spec = <{$money_format}>;<{/if}>
var Order = function() {
    var self = this;
    // this.member = !!Memory.get('member');
    <{if $minfo}>
    this.goods = {
        module: $('order_goods'),
        confirm: 'cart-goods_confirm.html',
        minfo: Cookie.read('checkout_b2c_goods_buy_info'),
        filled: function(json, input) {
            json = JSON.decode(json || self.goods.minfo);
            if(input !== true) {
                self.goods.module.getElements('.view-goods .memo').each(function(el, i){
                    if(json[i].name == 'minfo[product_id][]') {
                        json.erase(json[i]);
                    }
                    el.set('html', json[i].value);
                });
            } else {
                self.goods.module.getElements('.fill-goods [name^=minfo[]').each(function(el, i){
                    if(el.name != 'minfo[product_id][]' && json[i].name == el.name) {
                        el.set('value', json[i].value);
                    }
                });
            }
            return self;
        },
        fold: function() {
            if(self.goods.minfo) {
                var mod = self.goods;
                mod.edit.removeClass('fold');
                mod.view.removeClass('fold');
                mod.fill.addClass('fold');
                self.goods.filled(self.goods.minfo, true).goods.filled();
            }
            return self;
        }
    };
    Object.append(this.goods, {
        edit: this.goods.module.getElement('.action-edit-goods'),
        view: this.goods.module.getElement('.view-goods'),
        fill: this.goods.module.getElement('.fill-goods')
    });
    <{/if}>
    this.shipping = {
        module: $('order_shipping'),
        load: 'cart-shipping_edit.html',
        save: 'cart-shipping_save.html',
        remove: 'cart-shipping_delete.html',
        confirm: 'cart-shipping_confirm.html'
    };
    Object.append(this.shipping, {
        edit: this.shipping.module.getElement('.action-edit-shipping'),
        view: this.shipping.module.getElement('.view-shipping'),
        fill: this.shipping.module.getElement('.fill-shipping'),
        change: this.shipping.module.getElement('.change-shipping')
    });
    this.delivery = {
        module: $('order_delivery'),
        list: 'cart-delivery_change.html',
        confirm: 'cart-delivery_confirm.html'
    };
    Object.append(this.delivery, {
        edit: this.delivery.module.getElement('.action-edit-delivery'),
        view: this.delivery.module.getElement('.view-delivery'),
        change: this.delivery.module.getElement('.change-delivery')
    });
    this.payment = {
        module: $('order_payment'),
        list: 'cart-payment_change.html',
        confirm: 'cart-payment_confirm.html'
    };
    Object.append(this.payment, {
        edit: this.payment.module.getElement('.action-edit-payment'),
        view: this.payment.module.getElement('.view-payment'),
        change: this.payment.module.getElement('.change-payment')
    })
    <{if $tax_setting}>
    this.invoice = {
        module: $('order_invoice')
    };
    <{/if}>
    this.coupon = {
        module: $('order_coupon'),
        add: '<{link app=b2c ctl=cart act=add arg0=coupon}>',
        remove: 'cart-removeCartCoupon-coupon.html'
    };
    <{if $point_dis_html}>
    this.deduction = {
        module: $('order_deduction'),
        use: 'tools-count_digist.html'
    };
    <{/if}>
    this.isFastbuy = '<{if $is_fastbuy}>&isfastbuy=true<{/if}>';
    this.total = {
        module: $('order_price'),
        url: 'cart-total.html',
        update: function(callback) {
            var data = self.shipping.change.toQueryString() + '&' + self.delivery.change.toQueryString() + '&' + self.payment.change.toQueryString() + (self.invoice ? '&' + self.invoice.module.toQueryString() : '') + (self.deduction ? '&' + self.deduction.module.toQueryString() : '') + self.isFastbuy + '&extends_args=' + encodeURIComponent($('op_extends_args').value);
            self.update(self.total.url, data, self.total.module, callback);
        }
    };
    this.update = function(url, data, update, callback) {
        var Update = new Class({
            Extends: Request,
            options: {
                url: url,
                update: update,
                method: 'post',
                evalScripts: true,
                link: 'cancel',
                headers: {
                    Accept: 'text/html, application/xml, text/xml, */*'
                }
            },
            success: function(text){
                var options = this.options;
                var response = this.response;
                var json;
                try{
                    json = JSON.validate(text) ? JSON.decode(text, this.options.secure) : null;
                    if(json && json.error) return Message.error(json.error);
                }catch(e){}
                response.html = text.stripScripts(function(script){
                    response.javascript = script;
                });
                if (options.update){
                    options.update.set('html', response.html);
                    Browser.exec(response.javascript);
                }
                callback && callback(response.html, response.javascript);
            }
        });
        new Update(url, update, callback).send(data);
    };
    this.send = function(url, data, callback, update) {
        url = url || self[url];
        new Request({
            url: url,
            link: 'cancel',
            onComplete: function(rs){
                var json;
                try{
                    json = JSON.validate(rs) ? JSON.decode(rs) : null;
                    if(json && json.error) return Message.error(json.error);
                }catch(e){}
                callback && callback.call(this, rs, json);
            }
        }).send(data);
    };
}
var order = new Order();

Object.merge(validatorMap, {
    onesecond: function(element, v, type, parent){
        return parent.getElements('input[type=' + type + '][vtype='+ element.get('vtype') +']').some(function(el){
            el.onblur = function(){validate(this)};
            return el.value.trim() != '';
        });
    },
    requiredcustom: function(element, v, type, parent){
        var name = element.name;
        if(!parent.getElements('input[type=' + type + ']' + name ? '[name="' + name + '"]' : '').some(function(el) {
            return el.checked == true && el.value != '0';
        })) {
            showWarn(element, element.get('data-validatemsg'));
            return false;
        }
        return true;
    }
});

function selectArea(sels) {
    var selected = '';
    sels.each(function(s){
        if(s.isDisplayed()) {
            var text = s[s.selectedIndex].text.trim().clean();
            if(['<{t}>北京<{/t}>','<{t}>天津<{/t}>','<{t}>上海<{/t}>','<{t}>重庆<{/t}>'].indexOf(text)>-1) return;
            selected += text;
        }
    });
    // var arr = $('change_shipping').getElement('.action-change-shipping:checked');
    // if(arr) {
    //     var val = JSON.decode(arr.value);
    //     val.area = sels[0].getParent().getElement('input[name=area]').value;
    //     arr.value = JSON.encode(val);
    // }

    $('op_splice_area').innerHTML = selected;
    //$('addr_area').value = selected;
    //$('address').value = $('address').value.replace(selected, '');
};

function hideWarn(el, self) {
    el = self ? el : el.getParent('.order-section-content');
    el.retrieve('tips_instance', {hide: function(){}}).hide();
}
function showWarn(el, msg) {
    formTips.warn(msg, el.getParent('.order-section-content')).toElement().setStyle('margin-left', '4%');
    return false;
}

<{if $minfo}>
order.goods.fold();
<{/if}>
order.total.update();

$('main').addEvents({
    'click': function(e){
        var el = $(e.target);

        //= 点击document隐藏删除确认框
        var dtc = $$('.dialog-tips-container')[0];
        var target = $(document.body).retrieve('dialog-tip:show');
        var element;
        if(dtc && !dtc.contains(el) && target && !target.contains(el)) dtc.retrieve('instance').hide();

        if(el.getParent('.order-section')) {
            el.getParent('.order-section').removeClass('highlight');
            el.getParent('.order-section-content') && hideWarn(el);
        }
        //修复FF点击select闪烁的问题
        if(el.getParent('.fill-shipping') && el.getParent('li') && (el.match('option') || el.match('select') || el.match('input[type=text]'))) {
            e.preventDefault();
        }
    },
    //= 商品必填
    'click:relay(.action-confirm-goods)': function(e) {
        if(validate(this.getParent('.fill-goods'), 'all')) {
            loadGoods(this);
        }
    },
    //= 修改商品必填信息
    'click:relay(.action-edit-goods)': function(e) {
        e.stop();
        fold('goods', this);
    },
    //= 修改/取消修改
    'click:relay(.action-edit-shipping)': function(e) {
        e.stop();
        if(this.hasClass('action-cancel')) {
            var id = order.shipping.view.getElement('input[name=def_addr_id]').value;
            var radio = $('for_shipping_'+id);
            if(radio){
                switchSelected(radio.set('checked', true));
                radio.getParent('li').getElement('label').set('html', radio.getParent('li').retrieve('html:source'));
            }
        }
        fold('shipping', this);
        fold('delivery', 'notice', this.hasClass('action-cancel'));
        fold('payment', 'notice', this.hasClass('action-cancel'));
    },
    'click:relay(.action-edit-delivery)': function(e) {
        e.stop();
        fold('shipping', false);
        order.shipping.edit[!this.hasClass('action-cancel') ? 'addClass' : 'removeClass']('fold');
        fold('delivery', !this.hasClass('action-cancel'));
        fold('payment', 'notice', this.hasClass('action-cancel'));
    },
    'click:relay(.action-edit-payment)': function(e) {
        e.stop();
        fold('shipping', false);
        fold('delivery', false);
        fold('payment', !this.hasClass('action-cancel'));
    },
    //= 添加到常用地址
    'click:relay(.action-add-address)': function(e) {
        e.stop();
        var parent = this.getParent('.fill-shipping');
        if(validate(parent, 'all')) {
            addShipping(this);
        }
    },
    //= 编辑地址
    'click:relay(.action-edit-address)': function(e) {
        switchSelected(this, true);
    },
    //= 保存修改
    'click:relay(.action-save-address)': function(e) {
        e.stop();
        var parent = this.getParent('li');
        if(validate(parent, 'all')) {
            var checked = parent.getElement('.action-change-shipping');
            var area = parent.getElement('input[name=area]').value;
            var val = JSON.decode(checked.value);
            val.area = area.substr(area.lastIndexOf(':'));
            checked.value = JSON.encode(val);
            saveShipping(this);
        }
    },
    //= 删除地址
    'click:relay(.action-delete-address)': function(e) {
        e.stop();
        var msg = '<{t}>删除后不可恢复，确认删除此收货地址吗？<{/t}>';
        if(this.getParent('li').get('rel') == 'inuse') msg = '<{t}>此地址为修改前正在使用的收货地址，<{/t}>' + msg;
        Dialog.confirm(msg, function(e){
            e && deleteAddress(this);
        }.bind(this));
    },
    //= 确认收货地址
    'click:relay(.action-confirm-shipping)': function(e) {
        var parent = this.getParent('.change-shipping') || this.getParent('.fill-shipping');
        var li = parent.getElement('li.selected');
        if (li) {
            var checked = li.getElement('.action-change-shipping:checked');
            var fill = li.getElement('.fill-shipping');

            if(fill){
                if(validate(fill, 'all')) {
                    var val = JSON.decode(checked.value);
                    var area = fill.getElement('input[name=area]').value;
                    val.area = area.substr(area.lastIndexOf(':'));
                    checked.value = JSON.encode(val);
                    addShipping(checked, 'confirm');
                }
            }
            else {
                loadShipping(checked, 'confirm');
            }
            hideWarn(parent, true);
        }
        else if(validate(parent, 'all')) {
            addShipping(this, 'confirm');
        }
    },
    //= 确认配送方式
    'click:relay(.action-confirm-delivery)': function(e) {
        if(validate(this.getParent('.change-delivery'), 'all')) {
            order.shipping.edit.removeClass('fold');
            hideWarn(this);
            loadDelivery(this);
        }
    },
    //= 确认支付方式
    'click:relay(.action-confirm-payment)': function(e) {
        if(validate(this.getParent('.change-payment'), 'all')) {
            hideWarn(this);
            loadPayment(this);
        }
    },
    //= 订单优惠收起/展开
    'click:relay(.action-toggle)': function(e) {
        e.stop();
        this.set('text', this.hasClass('btn-collapse') ? '+' : '-').toggleClass('btn-collapse').toggleClass('btn-expand').getParent('h3').getNext('.content').toggle();
    },
    //= 使用订单优惠券
    'click:relay(.action-confirm-coupon)': function(e) {
        var parent = this.getParent('.item');
        var p = order.coupon.module;
        var ul = p.getElement('.usedlist');
        var cpn = ul.getElements('.action-cancel-coupon');
        var coupon = parent.getElement('select') || parent.getElement('input[type=text]');
        var value = coupon.value;
        if(coupon.match('select')) {
            var cpn_id = coupon.getSelected().get('data-coupon');
        }
        if(!value) return;
        if(cpn.length) {
            if(cpn.get('rel').indexOf(value) > -1 || cpn.get('data-code').indexOf(value) > -1 || cpn.get('data-coupon').indexOf(cpn_id) > -1) {
                coupon.value = '';
                return Dialog.alert('此优惠券已被使用！');
            }
        }
        new Request({
            url: '<{link app=b2c ctl=site_cart act=add arg0=coupon}>',
            link: 'cancel',
            onRequest: function() {
                p.getElements('input, select, button').set('disabled', true);
            },
            onComplete: function(rs) {
                rs = JSON.decode(rs);
                p.getElements('input, button').set('disabled', false);
                if(p.getElement('select').options.length > 1) p.getElement('select').disabled = false;
                if(rs.error){
                    //return Dialog.alert('优惠券添加失败，' + rs.error);
                }
                var data = rs.data;
                if(data) {
                    if(data.length) {
                        p.getElement('.used').removeClass('fold');

                        updateCoupon(ul, data);

                        coupon.value = '';
                        order.total.update();
                    } else {
                        Dialog.alert('优惠券添加失败，请明确优惠券的适用范围。');
                    }
                    p.getParent('form').getElement('input[name=md5_cart_info]').value = rs.md5_cart_info;
                }
            }
        }).post(parent.toQueryString() + '&is_fastbuy=<{$is_fastbuy}>&response_json=true');
    },
    //= 取消优惠券
    'click:relay(.action-cancel-coupon)': function(e) {
       
        e.stop();
        var p = order.coupon.module;
        var select = p.getElement('select');
        var data = 'cpn_ident=' + this.get('rel') + '&is_fastbuy=<{$is_fastbuy}>&response_json=true';
        order.send(order.coupon.remove, data, function(rs, json){
            var ul = p.getElement('.usedlist');
            var data = json.data;
            updateCoupon(ul, data);
            if(!data) {
                p.getElement('.used').addClass('fold');
            }
            window.location.reload();
            p.getParent('form').getElement('input[name=md5_cart_info]').value = json.md5_cart_info;
            order.total.update();
        });
    },
    //= 使用积分
    'click:relay(.action-confirm-score)': function(e) {
        var parent = this.getParent('.scoreinput');
        var value = parent.getElement('.action-input-score').value;
        if(!value) return;
        order.send(order.deduction.use, parent, function(rs){
            rs = {
                price: priceControl.format(rs),
                score: value
            };
            var tpl = '抵扣积分：<strong>{score}</strong> 抵扣金额：<b>{price}</b> <a href="javascript:void(0);" class="lnklike action-cancel-score">[取消使用]</a>';
            parent.addClass('fold');
            var xtip = $('xtips_container');
            if(xtip && xtip.isVisible()) xtip.retrieve('tips').hide();
            parent.getNext('.usedscore').set('html',tpl.substitute(rs)).removeClass('fold');
            order.total.update();
        });
    },
    //= 取消积分
    'click:relay(.action-cancel-score)': function(e) {
        e.stop();
        var p = order.deduction.module;
        p.getElement('.usedscore').addClass('fold');
        p.getElement('.scoreinput').removeClass('fold');
        p.getElement('.action-input-score').value = '';
        setPrice(0);
        order.total.update();
    },
    //= 提交订单
    'click:relay(.action-submit-order)': function(e) {
        if(!validateOrder()) {
            e.stop();
        }
    },
    //= 配送时间
    'change:relay(.action-assign-times)': function(e){
        var p = this.getParent();
        p.getElement('.assign-times')[this.checked ? 'show' : 'hide']();
        if(!this.checked) {
            p.getElement('.action-select-special').value = '任意日期';
            p.getElement('.action-select-times').value = '任意时间段';
        }
    },
    //= 指定配送时间
    'change:relay(.action-select-special)': function(e){
        this.getParent().getElement('.special-delivery-day')[this[this.selectedIndex].value == 'special' ? 'show' : 'hide']();
    },
    //= 选择/添加新收货地址
    'change:relay(.action-change-shipping)': function(e){
        var cond = this.value == 0;
        var li = this.getParent('li');
        var update = li.getElement('address');
        if(cond && li.getAllPrevious().length >= 10) {
            e.stop();
            li.getParent().getElement('li.selected .action-change-shipping').checked = true;
            return formTips.warn('最多添加10条，想要使用新收货地址，请先删除一条收货地址', update, {where: 'after', store: this.getParent('.change-shipping')});
        }
        switchSelected(this, cond);
    },
    //= 选择配送方式
    'change:relay(.action-change-delivery)': function(e){
        var parent = this.getParent('tr');
        if(parent.getSiblings('.sub').length) {
            parent.getSiblings('.sub').getElement('input[name=is_protect]').set('disabled', true);
            $(parent.id + '_sub') && $(parent.id + '_sub').getElement('input[name=is_protect]').set('disabled', false);
        }
    },
    //= 选择支付方式
    'change:relay(.action-change-payment)': function(e){
        var selected = this.getParent('tr').addClass('selected').getSiblings('tr.selected')[0];
        selected && selected.removeClass('selected');
    },
    //= 选择发票
    'change:relay(.action-select-invoice)': function(e){
        var cont = this.getParent('tr').getAllNext('tr');
        var need = this.getParent('.order-section-content').getElement('input[name="payment[is_tax]"]');
        cont[this.value == 'false' ? 'addClass' : 'removeClass']('fold');
        need.value = this.value == 'false' ? 'false' : 'true';
        order.total.update();
    }
});

//= 折叠/展开指定项
function fold(type, isfold, mod) {
    if(!type) return;
    type = type + '';
    var parent = order[type].module;
    var fill = parent.getElements('[class^=fill-]')
    var change = parent.getElement('[class^=change-]');
    var view = parent.getElement('[class^=view-]');
    var edit = parent.getElement('[class^=action-edit-]');
    var notice = parent.getElement('.notice');
    if(typeOf(isfold)=='element') {
        if(type == 'goods') {
            mod = 'fill';
        }
        fold(type, !isfold.hasClass('action-cancel'), mod);
    }
    else if(isfold === false) {
        view.removeClass('fold');
        fill && fill.addClass('fold');
        change && change.addClass('fold');
        notice && notice.addClass('fold');
        edit&&(edit.removeClass('fold').removeClass('action-cancel').innerHTML = '[修改]');
    }
    else if(isfold == 'notice' && notice) {
        if(mod) {
            Memory.set(type + '.stat', !edit || edit.hasClass('fold') ? notice && !notice.hasClass('fold') ? 'none' : 'noselect' : edit && edit.hasClass('action-cancel') ? 'editing' : 'view');
        }
        var stat = Memory.get(type + '.stat');
        if(!stat || stat === 'none') return;
        if(notice.hasClass('fold')) {
            notice.removeClass('fold');
            hideWarn(notice);
            parent.removeClass('highlight');
            view.addClass('fold');
            change&&change.addClass('fold');
            edit&&edit.addClass('fold');
        }
        else {
            notice.addClass('fold');
            if(stat == 'view') {
                view.removeClass('fold');
            }
            else {
                change&&change.removeClass('fold');
            }
            if(stat != 'noselect') {
                edit&&edit.removeClass('fold');
            }
        }
    }
    else {
        var who = mod !== 'fill' ? change : fill;
        who && who.removeClass('fold');
        view.addClass('fold');
        notice && notice.addClass('fold');
        edit&&(edit.addClass('action-cancel').innerHTML = '[取消修改]');
    }
}

//= 载入商品必填
function  loadGoods(el) {
    var parent = order.goods.module;
    var data = parent.getElement('.fill-goods');
    var view = parent.getElement('.view-goods');
    var goods_info = data.toJSON(true);

    fold('goods', false);
    Cookie.write('checkout_b2c_goods_buy_info', goods_info, {path:Shop.base_url});
    order.goods.filled(goods_info);
}
//设当前选中状态
function switchSelected(el, load) {
    var parent = (el.match('li') ? el : el.getParent('li')).addClass('selected');
    var label = parent.getElement('label');
    parent.retrieve('html:source') || label && parent.store('html:source', label.innerHTML);
    if(el.match('li') || el.hasClass('action-edit-address')) {
        if(Browser.ie) order.shipping.change.getElement('.action-change-shipping:checked').checked = false;
        parent.getElement('.action-change-shipping').checked = true;
    }
    load && loadShipping(el);
    var selected = parent.getSiblings('li.selected')[0];
    if(selected) {
        selected.removeClass('selected').retrieve('html:source') && selected.getElement('label').set('html', selected.retrieve('html:source'));
    }
}
//= 保存收货地址
function saveShipping(el) {
    var parent = el.getParent('li');
    var update = parent.getElement('label');
    order.update(order.shipping.save, parent, update, function(rs){
        switchSelected(parent);
        if(parent.hasClass('selected')) {
            order.shipping.edit.addClass('fold');
            order.delivery.edit.addClass('fold');
            order.payment.edit.addClass('fold');
        }
    });
}
//= 添加收货地址
function addShipping(el, method) {
    var method = method || 'save';
    var parent = el.getParent('li') || el.getParent('.fill-shipping');
    var update = parent.getElement('label') || el.getParent('.order-section-content').getElement('.view-shipping');
    var li;
    order.send(order.shipping.save, parent, function(rs){
        if(el.match('input')) {
            if(el.value == 0) {
                addAddress(update,parent,rs,true);
            }
            else {
                update.set('html', rs);
            }
        }
        else {
            addAddress(update,parent,rs);
        }
        if(method == 'confirm') {
            loadShipping(el.getParent('.order-section-content').getElement('.change-shipping .action-change-shipping:checked'), 'confirm');
            fold('shipping');
        }
    });
}
function addAddress(update, parent, rs, unfold) {
    var li;
    if(update.tagName == 'LABEL') {
        li = new Element('li', {html: rs}).inject(parent, 'before');
        update.set('html', parent.retrieve('html:source'));
    }
    else if(update.tagName == 'TABLE') {
        var inject = parent.addClass('fold').getParent().getElement('.change-shipping');
        li = new Element('li', {html: rs}).inject(inject, 'top');
        unfold&&inject.removeClass('fold');
    }
    switchSelected(li);
    order.shipping.edit.addClass('fold');
}
//= 删除收货地址
function deleteAddress(el) {
    var parent = el.getParent('li');
    var change = order.shipping.change;
    var data = parent.getElement('.action-change-shipping');
    order.send(order.shipping.remove, data.name+'='+data.value, function(rs){
        hideWarn(change, true);
        if(parent.hasClass('selected')) {
            order.shipping.edit.addClass('fold');
            //order.delivery.edit.addClass('fold');
            //order.payment.edit.addClass('fold');
        }
        parent.destroy();
        var cases = change.getElement('.action-change-shipping');
        if(cases.value == 0) {
            order.shipping.edit.addClass('fold');
            cases.checked = true;
            switchSelected(cases, true);
        }
    });
}
//= 载入填写收货信息区域
function loadShipping(el, method) {
    method = method || 'load';
    var parent;
    var update;
    if(method == 'load') {
        parent = el.getParent('li');
        update = parent.getElement('label');
    }
    else {
        parent = el.getParent('.change-shipping') || el.getParent('.fill-shipping');
        update = parent.getParent().getElement('.view-shipping');
    }
    order.update(order.shipping[method], parent, update, function(rs){
        bindDatepicker();
        if(method == 'confirm') {
            fold('shipping', false);

            var region = 'area=' + (parent.getElement('li.selected') ? JSON.decode(parent.getElement('li.selected').getElement('.action-change-shipping').value).area : parent.getElement('input[name=area]').value);
            linkage('delivery', region);
        }
    });
}
function loadDelivery(el) {
    var mod = order.delivery;
    var data = mod.change;
    var update = mod.view;
    order.update(mod.confirm, data.toQueryString() + order.isFastbuy, update, function(rs){
        fold('delivery', false);
        linkage('payment', data);
    });
}
function loadPayment(el) {
    var mod = order.payment;
    var data = mod.change;
    var update = mod.view;
    order.update(mod.confirm, data, update, function(rs){
        fold('payment', false);
        order.total.update();
    });
}
function linkage(next, data){
    var mod = order[next];
    var notice = mod.module.getElement('.notice');
    var change = mod.change;
    var view = mod.view;
    var edit = mod.edit;
    order.update(mod.list, data, change, function(rs){
        showWarn(change, mod.module.get('data-linkagemsg'));
        fold(next);
        edit.addClass('fold');
    });
}
function setPrice(el, rate) {
    var area = order.deduction.module;
    var value = typeOf(el) == 'element' ? priceControl.format(el.value * rate) : el;
    area.getElement('.action-deduct-price').set('text', value);
}

function updateCoupon(el, data){
    var tpl = '<li><i title="{name}">{coupon}-{name}</i><a href="javascript:void(0);" class="lnklike action-cancel-coupon" rel="{obj_ident}" data-coupon="{cpns_id}">[取消使用]</a></li>';
    var html = '';
    if(data && data.length) {
        data.each(function(d){
            html += tpl.substitute(d);
        });
    }
    el.innerHTML = html;
}

function validateOrder(){
    var error = ['goods', 'shipping', 'delivery', 'payment'].some(function(view, i){
        var mod = order[view];
        if(!mod) return;
        if(mod.module && mod.view.hasClass('fold')) {
            mod.module.addClass('highlight');
            Dialog.alert(mod.module.get('data-validatemsg'), function(){
                new Fx.Scroll(window,{duration:250, link:'ignore'}).toElementEdge(mod.module);
            });
            return true;
        }
        mod.module.removeClass('highlight');
    });
    if(error) return false;
    return true;
}

if(order.deduction) {
    var inputscore = order.deduction.module.getElement('.action-input-score');
    var inputscorevalue = '';
    //= 积分输入
    inputscore.addEvents({
        'inputchange': function(e){
            var parent = this.getParent('.content');
            var max = Math.min(parent.getElement('.action-max-score').get('text'), parent.getElement('.action-user-score').get('text'));
            var rate = parent.getElement('input[name="point[rate]"]').value;
            var price = parent.getElement('.action-deduct-price');
            if(this.value == 0) {
                this.value == '';
                return;
            }
            if(isNaN(this.value)) {
                this.value = inputscorevalue;
                //setPrice(0);
                return;
            }
            if(!this.value.test(/^(0|[1-9][0-9]*)?$/)) {
                this.value = this.value.substr(0, this.value.length - 1);
                return;
            }
            if(Number(this.value) > max) {
                inputscorevalue = this.value = max;
                setPrice(this, rate);
                return this.tips('本次能使用的最大积分为' + max);
            }
            inputscorevalue = this.value;
            setPrice(this, rate);
        },
        'enter': function(e){
            e.stop();
        }
    });
}
//= 最大字符300
var textarea = $('order_clearing').getElement('.action-remark-textarea').addEvent('inputchange', function(e){
    if(this.value.length > 300) {
        this.tips('订单备注最多输入300字').value = this.value.substr(0, 300);
    }
});


window.addEvent('domready', function(){
	 var sub = document.getElementById("for_delivery_3");
	 if(sub)sub.click();
	 
	 var confirm_delivery = document.getElementById("action-confirm-delivery");
	 if(confirm_delivery)confirm_delivery.click();
	
});
</script>

    
<script type="text/javascript">
(function() {
<{if !$is_empty}>
<{if $money_format}>
    priceControl.spec = <{$money_format}>;
<{/if}>
    var container = $('cart_container');
    var typeJSON = {
        'product': ['商品', '购买'],
        'packs': ['礼包', '购买'],
        'exchange': ['赠品', '兑换']
    };

    //= 获取商品属性值
    function getTypeValue(type) {
        if(!type) return null;
        var value = typeJSON[type];
        if(typeof value == 'string') value = [value, '购买'];
        return {name:value[0], mode: value[1]};
    }
    
    //== 商品数量输入框正确性检测
    function inputCheck(input, options) {
        if(!input) return false;
        options = options || {};
        if(isNaN(options.min)) options.min = 1;
        if(isNaN(options.max)) options.max = 9999;
        options.type = options.type || 'product';
        options['default'] = options['default'] || options.min;
        var info = getTypeValue(options.type);
        var value = +input.value;
        var tips = new Tips(input);
        var pre = '';
        var msg = '';
        if(options.store && options.store - value <= 0) {
            pre = '库存有限，';
        }
        if(value < options.min) {
            input.value = options.min;
            msg = '此' + info.name + '的最小' + info.mode + '数量为' + options.min + '件';
        }
        else if(value > options.max){
            input.value = options.max;
            msg = pre + '此' + info.name + '最多只能' + info.mode + options.max + '件';
        }
        else if(isNaN(value)) {
            input.value = options['default'];
            msg = '只允许输入数字';
        }
        if (msg) {
            tips.show(msg);
            return false;
        }
        tips.hide();
        //warn.hide();
        if(options.type == 'packs') {
            input.getParent('.cart-item').getElements('.p-packs-item .p-num').set('text', value);
        }
        input.value = parseInt(value);
        return true;
    }
    
    //== 获取商品数量值
    function getQuantity(el, type) {
        return el.getElement('input[name=' + type + ']').value;
    }
    
    //== 设置商品数量
    function setQuantity(input, value) {
        var type = input.getParent('.p-packs') ? 'packs' : input.getParent('.cart-exchange') ? 'exchange' : 'product';
        var typeName = typeJSON[type];
        var p = input.getParent('tr');
        if(!inputCheck(input, {min: getQuantity(p, 'min'), max: getQuantity(p, 'max'), 'default': value, type: type, store: getQuantity(p, 'stock')}) && input.value == value) {
            return;
        }
        new Request({
            url: '<{link app=b2c act=update ctl=site_cart}>',
            data: p.toQueryString()+"&response_json=true",
            onComplete: function(rs){
                rs = JSON.decode(rs);
                if(rs.success) {
                    updateCart(rs, p);
                }
            }
        }).post();
    }
    
    //== 更新购物车信息统一入口
    function updateCart(rs, p){
        if(!rs) return;
        if(p) {
            updateGoodsInfo(rs.edit_ajax_data, p);
            rs.promotion && updateGoodsPromotion(rs.promotion.goods, p);
        }
        updateOrderInfo(rs.sub_total);
        updateOrderInfos(rs.sub_total);
        updateOrderGift(rs.order_gift);
        <{if $cart_promotion_display == 'true'}>
        rs.promotion && updateOrderPromotion(rs.promotion.order);
        updateUnusePromotion(rs.unuse_rule);
        <{/if}>
        updateCartInfo();
    }
    
    //== 更新购物车价格/优惠等
    function updateGoodsInfo(rs,product) {
        if(!rs) return;
        try{
            product.getElement('.p-integral').innerHTML = Number(rs.consume_score) || '-';
            product.getElement('.p-discount').innerHTML = rs.discount || '-';
            product.getElement('.p-subtotal').innerHTML = rs.buy_price || '-';
        }catch(e){}
    }
    
    //== 更新商品促销
    function updateGoodsPromotion(rs, product) {
        if(!rs) return;
        var tmpl = '<li><b>[{desc_tag}]</b>{name}</li>';
        container.getElements('tbody tr.cart-product').each(function(item){
            var html = '';
            var ident = item.getElement('input[name=goods_ident]');
            if(!ident) return;
            var promoarea = item.getElement('.p-promotion ul');
            var identifier = ident.value;
            var item = rs[identifier];
            if(item && item.length) {
                item.each(function(item){
                    if(item.cart_display) html += tmpl.substitute(item);
                });
                promoarea.innerHTML = html;
            }
        });
    }
    //== 更新订单信息
    function updateOrderInfo(rs) {
        if(!rs) return;
        var order = $('order_price');
        if(order.getElement('.subtotal-integral')) order.getElement('.subtotal-integral').innerHTML = rs.subtotal_gain_score;
        if(order.getElement('.discount .price')) {
            if(rs.discount_amount_order) {
                order.getElement('.discount').show();
                order.getElement('.discount .price').innerHTML = rs.discount_amount_order;
            }
            else order.getElement('.discount').hide();
        }
        order.getElement('.goods .price').innerHTML = rs.subtotal_prefilter_after;
        order.getElement('.total .price b').innerHTML = rs.promotion_subtotal;
        winReloadd();
        // 更新订单总金额存储
        // Memory.set('cart_total_price', rs.promotion_subtotal);
    }
    
    //== 更新订单信息
    function updateOrderInfos(rs) {
        if(!rs) return;
        var order = $('order_prices');
        var dede = $('kkkkk');
        var dsds = $('sssss');
        var dfdf = $('fffff');
        if(order.getElement('.subtotal-integral')) order.getElement('.subtotal-integral').innerHTML = rs.subtotal_gain_score;
        if(order.getElement('.discount .price')) {
            if(rs.discount_amount_order) {
                order.getElement('.discount').show();
                order.getElement('.discount .price').innerHTML = rs.discount_amount_order;
            }
            else order.getElement('.discount').hide();
        }
        order.getElement('.goods .price').innerHTML = rs.subtotal_prefilter_after;
        order.getElement('.total .price b').innerHTML = rs.promotion_subtotal;
        order.getElement('.goodst').innerHTML = '';
        dede.getElement('.kkss').innerHTML = rs.promotion_subtotal;
        dsds.getElement('.kkdd').innerHTML = '<input id=txtAmount value="'+rs.promotion_subtotal+'" readOnly="true" style="border:none; color: red; font-size: 24px; font-weight: bold;height:28px;margin-top:-6px;" />';
        dfdf.getElement('.kkff').innerHTML = '<b>'+rs.promotion_subtotal+'</b>';
        // 更新订单总金额存储
        // Memory.set('cart_total_price', rs.promotion_subtotal);
        // 验证预付款金额
        checkPreMoney();
        winReloadd();
    }

    //== 更新订单赠品区
    function updateOrderGift(rs) {
        var giftarea = $('order_gift');
        var tmpl = '<tr class="cart-item"><td><div class="p-pic"><a href="{url}"><img src="{thumbnail}" alt="{name}"></a></div></td><td class="p-info"><div class="p-title"><a href="{url}">{name}</a></div><div class="p-spec">{spec_info}</div></td><td class="p-price">{price}</td><td class="p-num">{quantity}</td><td colspan="4"></td></tr>';
        try{
            giftarea.getElements('.cart-item').destroy();
        }catch(e){}
        if(!rs) {
            return giftarea.hide();
        }
        var html = '';
        var item = rs;
        if(item && item.length) {
            item.each(function(item){
                item.buy_price = item.price.buy_price || priceControl.format(0);
                html += tmpl.substitute(item);
            });
        }
        giftarea.show().set('html', giftarea.get('html') +html);
    }
    <{if $cart_promotion_display == 'true'}>
    //== 更新订单促销
    function updateOrderPromotion(rs) {
        var area = $('order_promotion');
        if(!rs) area.hide();
        var tmpl = '<li><b>[{desc_tag}]</b>{name}</li>';
        var html = '';
        var promoarea = area.getElement('.content');
        var item = Object.values(rs);
        if(item && item.length) {
            area.show();
            item.each(function(item){
                html += tmpl.substitute(item);
            });
        }
        promoarea.innerHTML = html;
    }
    //== 更新未使用的促销
    function updateUnusePromotion(rs){
        var area = $('unused_promotion');
        if(!rs) area.hide();
        var tmpl = '<li><b>[{desc_tag}]</b>{name}</li>';
        var html = '';
        var promoarea = area.getElement('.content');
        var item = Object.values(rs);
        if(item && item.length) {
            area.show();
            item.each(function(item){
                html += tmpl.substitute(item);
            });
        };
        promoarea.innerHTML = html;
    }
    <{/if}>

    //== 为数量选择框绑定事件
    function bindQuantityEvent(elements, callback) {
        elements = document.id(elements) || $$(elements);
        if(!elements || !elements.length) return;
        var value = '';
        elements.addEvents({
            //= 数量按钮
            'click:relay(.btn-decrease,.btn-increase)': function(e) {
                var input = this.getParent().getElement('input');
                value = +input.value;
                input.value = this.hasClass('btn-decrease') ? value - 1 : value + 1;
                callback && callback(input, value);
            },
            //= 数量输入框
            'focus:relay(input)': function(e){
                value = +this.value;
            },
            'change:relay(input)': function(e) {
                try{
                    var _dom  = e.target || e.srcElement,
                        _val  = parseFloat(_dom.value) / 1000,
                        _val  = _val.toFixed(3),
                        _e_id = _dom.id.replace('modify_quantity', 'modify_quantity_ex');
                    $(_e_id).value = _val;
                } catch(e) {}
                callback && callback(this, value);
                
            }
            
        });
    }
    bindQuantityEvent('.p-quantity', setQuantity);
    
    //== 大的数量换算为小数量
    function bindQuantityExchangeEvent(elements, callback) {
        elements = document.id(elements) || $$(elements);
        if(!elements || !elements.length) return;
        var value = '';
        elements.addEvents({
            'change:relay(input)': function(e) {
                try{
                    var _dom  = e.target || e.srcElement,
                        _val  = parseInt(parseFloat(_dom.value) * 1000),
                        _e_id = _dom.id.replace('modify_quantity_ex', 'modify_quantity'),
                        _e_dom= $(_e_id);
                    _e_dom.value = _val;
                    callback && callback(_e_dom, _val);
                } catch(e) {}
            }
        });
    }
    bindQuantityExchangeEvent('.p-goodskg', setQuantity);

    $('main').addEvents({
        'click': function(e){
            var el = $(e.target);

            //==点击document隐藏删除确认框
            var dtc = $$('.dialog-tips-container')[0];
            var target = $(document.body).retrieve('dialog-tip_show');
            if(dtc && dtc.retrieve('instance') && !dtc.contains(el) && target && !target.contains(el)) dtc.retrieve('instance').hide();
        },
        //= 移除商品
        'click:relay(.btn-delete)': function(e) {
            Dialog.tips(this, '确定将商品从购物车中移除吗？', function(e){
                if(e) {
                    var p = this.getParent('tr.p-adjunct') || this.getParent('.cart-item') || this.getParent('tr.item');
                    new Request({
                        url:'<{link app=b2c ctl=site_cart act=remove}>',
                        data: p.toQueryString()+"&response_json=true",
                        onRequest: function() {
                            p.mask({html:'处理中...','class':'cover',injectTo:document.body,position:true,effect:false, resize: false});
                        },
                        onComplete:function(rs) {
                            rs = JSON.decode(rs);
                            if(rs.is_empty) return location.reload();
                            p.unmask();
                            if(rs.error) return Message.error(rs.error);
                            if(p.hasClass('item') && $('cart_exchange').getChildren().length == 2) $('cart_exchange').destroy();
                            else p.destroy();
                            updateCart(rs, p);
                            var _url = '<{link app=b2c ctl=site_cart act=index}>?type=x';
                            window.location.href = _url;
                        }
                    }).post(p.get('data-product'));
                }
            }.bind(this));
            document.body.store('dialog-tip_show', this);
        },
        //= 订单优惠收起/展开
        'click:relay(.action-toggle)': function(e) {
            e.stop();
            this.set('text', this.hasClass('btn-collapse') ? '+' : '-').toggleClass('btn-collapse').toggleClass('btn-expand').getParent('h3').getNext('.content').toggle();
        },
        //= 凑单
        'click:relay(.action-fororder)': function(e) {
            e.stop();
            var dialog = new Dialog('<{link app=b2c ctl=site_cart act=fororder}>', {
                title: '凑单商品',
                width: 960,
                height: 330,
                modal:true,
                async: 'ajax'
            });
        },
        <{if $login == 'nologin' && $env.conf.b2c.site.login_type == 'target'}>
        'click:relay(.action-settle)': function(e) {
            e.stop();
            miniPassport('<{link app=b2c ctl=site_cart act=loginBuy}>', function(dialog){
                this.removeClass('disabled');
            }.bind(this));
        },
        <{/if}>
        //= 清空购物车
        'click:relay(.action-clean)': function(e) {
            Dialog.confirm('确定清空购物车吗？', function(e){
                if(e) {
                    new Request({
                        url:'<{link app=b2c ctl=site_cart act=remove}>',
                        data:'obj_type=all&response_json=true',
                        onRequest: function() {
                            container.mask({html:'处理中...','class':'cover',position:true,effect:false, resize: false});
                        },
                        onSuccess:function(rs) {
                            rs = JSON.decode(rs);
                            container.unmask();
                            if(rs.error) return Message.error(rs.error);
                            location.reload();
                        }
                    }).post();
                }
            });
        }
    });

    //== 商品图片缩放
    if(Browser.ie6) {
        container.getElements('.p-pic img').each(function(img){
            img.zoomImg(80,80);
        });
    }
<{/if}>

    //浏览历史
    withBrowserStore(function(browserStore) {
        var box = $('view_history');
        if ( !box ) {
            return false;
        }
        // $('clear_history').addEvent('click', function(){browserStore.clear('history');box.hide();});
        browserStore.get('history', function(rs) {
            rs = JSON.decode(rs);
            var min = 1;
            if (!rs || rs.length <= min) return box.hide();

            var html = '';
            var template = '<li class="item">';
            template += '<div class="p-pic">';
            template += '  <a href="<{link app=b2c ctl=site_product act=index arg0="{goodsId}"}>" target="_blank" title="{goodsName}" data-gid="{goodsId}"><img src="{goodsImg}" alt="{goodsName}" /></a>'.replace('index-', '');
            template += '</div>';
            template += '<div class="p-info">';
            template += '  <h3><a href="<{link app=b2c ctl=site_product act=index arg0="{goodsId}"}>" target="_blank" title="{goodsName}">{goodsName}</a></h3>'.replace('index-', '');
            template += '  <p class="p-price">{price}</p>';
            template += '  <a href="<{link app=b2c ctl=site_product act=index arg0="{goodsId}"}>" target="_blank" class="btn btn-major"><span><span><{t}>立即购买<{/t}></span></span></a>'.replace('index-', '');
            template += '</div>';
            template += '</li>';

            var max = Math.min(rs.length, <{$setting.max|default:8}>);

            // rs.length > 1 && rs.sort(function(a, b) {
            //     return b['sortTime'] - a['sortTime'];
            // });

            rs.each(function(goods, index) {
                if (index >= min && index <= max) html += template.substitute(goods);
            });

            box.getElement('ul').innerHTML = html;

            box.getElements('.p-pic a').each(function(item) {
                var img = item.getElement('img');
                img.zoomImg(96,96);
                img.onerror = function(){
                    imgRequest(item, img, rs, min, max);
                }
                if (!img.get('src')) {
                    imgRequest(item, img, rs, min, max);
                }
            });
        });

        function imgRequest(el, img, rs, min, max) {
            var gid = el.get('data-gid');
            new Request.JSON({
                url: "<{link app=b2c ctl=site_product act=picsJson}>",
                onComplete: function(data) {
                    new Asset.image(data, {
                        onload: function() {
                            img.src = data;
                            img.zoomImg(96,96);
                        },
                        onerror: function() {
                            el.set('text', '<{t}>图片加载失败<{/t}>');
                        }
                    });

                    rs.map(function(goods, index) {
                        if (index >= min && index <= max && goods['goodsId'] == gid) return goods['goodsImg'] = data;
                    });

                    browserStore.set('history', JSON.encode(rs));
                }
            }).get({'gids': gid});
        }   
    });
})();

/**
 * 验证预付款金额
 *
 * @return  bool
 */
function checkPreMoney() {
    var dede = $('kkkkk');
    var zhye_val    = dede.getElement('.kkss1').innerHTML;
    var ysje_val    = dede.getElement('.kkss').innerHTML;
    zhye_val        = zhye_val.match(/\d+(?:\.\d+)?$/)[0];
    ysje_val        = ysje_val.match(/\d+(?:\.\d+)?$/)[0];
    zhye_val        = parseFloat(zhye_val);
    ysje_val        = parseFloat(ysje_val);
    var z_o_dom     = dede.getElement('.zhye_other');
    if ( zhye_val < ysje_val ) {
        var _val    = ysje_val - zhye_val;
        _val    = _val.toFixed(2);
        dede.getElement('.zhye_other_val').innerHTML = '￥' + _val;
        z_o_dom.show();
        return false;
    } else {
        z_o_dom.hide();
        return true;
    }
}
// 验证初始化页面时付款数据
checkPreMoney();
function winReloadd() {
    var _url = '<{link app=b2c ctl=site_cart act=index}>'+'?type=x';
    window.location.href = _url;
}
</script>
